package com.qinggeng.framework.interceptor.impl;

import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.common.utils.file.FileUtils;
import com.qinggeng.framework.web.domain.AjaxResult;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

@Component
public class FileUploadInterceptor implements HandlerInterceptor {

    @Value("${guoshuda.maxSize}")
    private Long maxUploadSize;

    private Boolean checkMime=false;

    private String allowMimes="";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("TimeInterceptor 进入 Controller 某个方法之前");

        request.setAttribute("startTime", new Date().getTime());

        // 未设定最大上传文件大小
        if (maxUploadSize == null || maxUploadSize <= 0) {
            return true;
        }
        // 判断是否文件上传
        if (request != null && ServletFileUpload.isMultipartContent(request)) {
            ServletRequestContext ctx = new ServletRequestContext(request);
            // 获取上传文件尺寸大小
            long requestSize = ctx.contentLength();
            FileUtils.checkSize(maxUploadSize, requestSize);
            // 验证文件类型
            if (checkMime != null && checkMime == true) {
                check(request);
            }

        }
        return true;

    }

    /**
     * 判断是否为允许的上传文件类型
     */
    private boolean checkMime(String ext) {
        if (this.allowMimes.contains(ext.toLowerCase())) {
            return true;
        }
        return false;
    }

    private boolean check(HttpServletRequest request){

        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> files = multipartRequest.getFileMap();
            Iterator<String> iterator = files.keySet().iterator();
            // 对多部件请求资源进行遍历
            while (iterator.hasNext()) {
                String formKey = iterator.next();
                MultipartFile multipartFile = multipartRequest.getFile(formKey);
                String filename = multipartFile.getOriginalFilename();
                String ext = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
                // 判断是否为限制文件类型
                if (!checkMime(ext)) {
                    throw new CustomException("File type '" + ext + "' unsupport.");
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("TimeInterceptor 运行 Controller 某个方法时，方法抛出异常将不进入此方法");
        long start = (long) request.getAttribute("startTime");
        System.out.println("TimeInterceptor 处理时长为："+ (new Date().getTime() - start));

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("TimeInterceptor 完成 Controller 某个方法");
        long start = (long) request.getAttribute("startTime");
        System.out.println("TimeInterceptor 处理时长为："+ (new Date().getTime() - start));

    }

}
